'use client';

import React, { useState, useEffect } from 'react';
import { 
  Card, Row, Col, Input, Select, Button, Table, Form, 
  Modal, message, Space, Popconfirm, InputNumber, DatePicker, Radio
} from 'antd';
import { 
  SearchOutlined, PlusOutlined, EditOutlined, 
  DeleteOutlined
} from '@ant-design/icons';
import { 
  fetchEmployeeData, updateEmployeeProfile, deleteEmployees, 
  addEmployee, getUserInfo,fetchSingleEmployee
} from '@/lib/user';
import { getAllDepartments } from '@/lib/departments';
import { getAcademies } from '@/lib/academy';
import { getOtherDepts } from '@/lib/otherdept';
import Layout from '@/components/Layout';
import { fetchRoles } from '@/lib/role';
import styled from '@emotion/styled';
import dayjs from 'dayjs';

const { Option } = Select;

const StyledModal = styled(Modal)`
  .ant-modal-content {
    max-height: 90vh;
    margin: 50px auto 0; // 添加上边距
    display: flex;
    flex-direction: column;
    border-radius: 8px;
    overflow: hidden;
  }
  
  .ant-modal-header {
    padding: 16px 24px;
    border-bottom: 1px solid #f0f0f0;
  }

  .ant-modal-close {
    top: 16px; // 调整关闭按钮位置
  }
  
  .ant-modal-body {
    max-height: calc(90vh - 170px); // 调整内容区域高度
    overflow-y: auto;
    padding: 24px;
    
    &::-webkit-scrollbar {
      width: 6px;
    }
    
    &::-webkit-scrollbar-track {
      background: #f0f0f0;
      border-radius: 3px;
    }
    
    &::-webkit-scrollbar-thumb {
      background: #ccc;
      border-radius: 3px;
      
      &:hover {
        background: #999;
      }
    }
  }

  .ant-modal-footer {
    border-top: 1px solid #f0f0f0;
    padding: 16px 24px;
  }
`;

// 1. 添加状态类型定义
interface UserInfo {
  employeeId: string;
  username: string;
  gender: number | null;
  age: number | null;
  birthday: string | null; 
  phoneNumber: string | null;
  email: string | null;
  department: number;
  deptName: string;
  deptType: number;
  position: string;
  status: number;
  role: string;
}

// 1. 修改状态映射常量，包含试用期状态
const STATUS_MAP = {
  0: '试用期员工',
  1: '正式员工',
  2: '离职'
};

interface Department {
  value: string;
  label: string;
  positions: any[];
  type: 'dept' | 'academy' | 'other';
}

interface DepartmentGroup {
  label: string;
  options: Department[];
}

interface TableParams {
  current?: number;
  pageSize?: number;
  [key: string]: any;
}

interface DeptData {
  deptId: number;
  deptName: string;
  positions: Position[];
}

interface AcademyData {
  academyId: number;
  academyName: string;
  positions: Position[];
}

interface OtherDeptData {
  otherDeptId: number;
  otherDeptName: string;
  positions: Position[];
}

interface Position {
  positionId: number;
  positionName: string;
}

interface Role {
  id: number;
  name: string;
}

interface ApiError {
  response?: {
    data?: {
      msg?: string;
    };
  };
  message?: string;
}

const ERROR_MESSAGES: Record<string, string> = {
  'error': '操作失败',
  '不可以修改自己的信息！': '您不能修改自己的信息，请联系其他管理员进行修改',
  'unauthorized': '您没有权限执行此操作',
  'invalid_data': '提交的数据无效，请检查后重试'
};

interface TableChangeParams {
  current?: number;
  pageSize?: number;
  filters?: Record<string, any>;
  sorter?: Record<string, any>;
}

const DEPT_TYPE_MAP: Record<number, string> = {
  1: '职能部门',
  2: '二级学院',
  3: '其他部门'
};

interface TableColumn {
  title: string;
  dataIndex?: string;
  key: string;
  align?: 'left' | 'right' | 'center';
  render?: (value: any, record: UserInfo) => React.ReactNode;
}

// 定义 fetchEmployeeData 的参数类型
interface FetchEmployeeDataParams {
  page?: number;
  pageSize?: number;
  keyword?: string;
  department?: string | number;
  deptType?: number;
  position?: string | number;
  [key: string]: any;
}

const UserInfoPage = () => {
  const [users, setUsers] = useState<UserInfo[]>([]);
  const [allUsers, setAllUsers] = useState<UserInfo[]>([]);
  const [departments, setDepartments] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [selectedDepartment, setSelectedDepartment] = useState('');
  const [modalVisible, setModalVisible] = useState(false);
  const [modalMode, setModalMode] = useState('add');
  const [editingUser, setEditingUser] = useState<UserInfo | null>(null);
  const [form] = Form.useForm();
  const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]);
  const [currentUser, setCurrentUser] = useState<UserInfo | null>(null);
  const [roles, setRoles] = useState<any[]>([]); 
  const [allDepartments, setAllDepartments] = useState<DepartmentGroup[]>([]);
  const [positions, setPositions] = useState<any[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });
  const [filters, setFilters] = useState({
    keyword: '',
    department: undefined as string | undefined,
    deptType: undefined as number | undefined,
    position: undefined as string | undefined
  });

  useEffect(() => {
    loadDepartments();
    loadUsers();
    loadCurrentUser();
    loadRoles();
    loadAllDepartments();
  }, []);

  const loadCurrentUser = async () => {
    try {
      const response = await getUserInfo();
      console.log(response)
      if (response.data && response.data.code === 1) {
        setCurrentUser(response.data.data);
      } else {
        throw new Error(response.data?.msg || '获取用户信息失败');
      }
    } catch (error) {
      console.error("获取用户信息失败", error);
      message.error('获取用户信息失败，请检查网络或重新登录');
    }
  };

  const loadDepartments = async () => {
    try {
      const response = await getAllDepartments();
      console.log("部门数据:", JSON.stringify(response, null, 2));
      if (response.data && response.data.code === 1) {
        setDepartments(response.data.data);
      } else {
        message.error('获取部门数据失败');
      }
    } catch (error) {
      console.error("获取部门数据失败", error);
      message.error('获取部门数据失败，请检查网络或联系管理员');
    }
  };

  const loadUsers = async (params?: TableChangeParams) => {
    setLoading(true);
    
    try {
      // 如果只输入了7位数字工号，使用工号查询
      if (filters.keyword && /^\d{7}$/.test(filters.keyword) && 
          !filters.department && !filters.deptType && !filters.position) {
        console.log('执行工号查询:', filters.keyword);
        const response = await fetchSingleEmployee(filters.keyword);
        console.log('工号查询响应:', response.data);
        
        if (response.data && response.data.code === 1) {
          const userData = response.data.data;
          if (userData && userData.row && userData.row.length > 0) {
            setUsers(userData.row);
            setPagination(prev => ({
              ...prev,
              total: userData.total || userData.row.length,
              current: 1,
              pageSize: 10
            }));
          } else {
            setUsers([]);
            setPagination(prev => ({
              ...prev,
              total: 0,
              current: 1,
              pageSize: 10
            }));
            message.info('未找到该员工');
          }
        } else {
          setUsers([]);
          setPagination(prev => ({
            ...prev,
            total: 0,
            current: 1,
            pageSize: 10
          }));
          message.error(response.data?.msg || '查询失败');
        }
        setLoading(false);
        return;
      }

      // 条件查询
      const queryParams: FetchEmployeeDataParams = {
        page: params?.current || pagination.current,
        pageSize: params?.pageSize || pagination.pageSize,
      };

      // 添加其他筛选条件
      if (filters.keyword && !/^\d{7}$/.test(filters.keyword)) {
        queryParams.username = filters.keyword;
      }
      if (filters.department) {
        queryParams.department = parseInt(filters.department);
      }
      if (filters.deptType !== undefined && filters.deptType !== null) {
        // 确保 deptType 是数字类型
        queryParams.deptType = Number(filters.deptType);
      }
      if (filters.position) {
        queryParams.position = parseInt(filters.position);
      }

      console.log('条件查询参数:', queryParams);
      
      const response = await fetchEmployeeData(queryParams);
      console.log('条件查询响应:', response.data);
      
      if (response.data && response.data.code === 1) {
        const { total, row } = response.data.data;
        setUsers(row || []);
        setPagination(prev => ({
          ...prev,
          total: total || 0,
          current: params?.current || pagination.current,
          pageSize: params?.pageSize || pagination.pageSize
        }));
      } else {
        setUsers([]);
        message.error(response.data?.msg || '获取用户列表失败');
      }
    } catch (error: unknown) {
      console.error('查询失败:', error);
      setUsers([]);
      if (error instanceof Error) {
        message.error(error.message || '查询失败');
      } else {
        message.error('查询失败');
      }
    } finally {
      setLoading(false);
    }
  };

  const loadRoles = async () => {
    try {
      const response = await fetchRoles();
      console.log(response)
      if (response.data && response.data.code === 1) {
        const rolesData = response.data.data.roles || [];
        setRoles(rolesData);
      } else {
        message.error('获取角色数据失败');
      }
    } catch (error) {
      console.error("获取角色数据失败", error);
      message.error('获取角色数据失败，请检查网络或联系管理员');
    }
  };

  const loadAllDepartments = async () => {
    try {
      const [deptRes, academyRes, otherDeptRes] = await Promise.all([
        getAllDepartments(),
        getAcademies(),
        getOtherDepts()
      ]);

      const deptGroups: DepartmentGroup[] = [];

      // 处理职能部门
      if (deptRes.data?.code === 1 && deptRes.data.data) {
        const deptOptions = deptRes.data.data.map((dept: DeptData) => ({
          value: `dept_${dept.deptId}`,
          label: dept.deptName,
          positions: dept.positions,
          type: 'dept' as const
        }));
        deptGroups.push({
          label: '职能部门',
          options: deptOptions
        });
      }

      // 处理学院
      if (academyRes.data?.code === 1 && academyRes.data.data) {
        const academyOptions = academyRes.data.data.map((academy: AcademyData) => ({
          value: `academy_${academy.academyId}`,
          label: academy.academyName,
          positions: academy.positions,
          type: 'academy' as const
        }));
        deptGroups.push({
          label: '二级学院',
          options: academyOptions
        });
      }

      // 处理其他部门
      if (otherDeptRes.data?.code === 1 && otherDeptRes.data.data) {
        const otherOptions = otherDeptRes.data.data.map((other: OtherDeptData) => ({
          value: `other_${other.otherDeptId}`,
          label: other.otherDeptName,
          positions: other.positions,
          type: 'other' as const
        }));
        deptGroups.push({
          label: '其他部门',
          options: otherOptions
        });
      }

      setAllDepartments(deptGroups);
    } catch (error) {
      console.error("获取部门数据失败", error);
      message.error('获取部门数据失败，请检查网络或联系管理员');
    }
  };

  const handleSearch = () => {
    console.log('执行搜索，当前筛选条件:', filters);
    setPagination(prev => ({
      ...prev,
      current: 1
    }));
    loadUsers({
      current: 1,
      pageSize: pagination.pageSize
    });
  };

  const handleReset = () => {
    console.log('重置筛选条件');
    setFilters({
      keyword: '',
      department: undefined,
      deptType: undefined,
      position: undefined
    });
    
    setPagination(prev => ({
      ...prev,
      current: 1
    }));
    
    // 延迟执行查询，确保状态已更新
    setTimeout(() => {
      loadUsers({
        current: 1,
        pageSize: pagination.pageSize
      });
    }, 0);
  };

  const handleTableChange = (
    pagination: TableChangeParams,
    filters: Record<string, any>,
    sorter: Record<string, any>
  ) => {
    loadUsers({
      current: pagination.current,
      pageSize: pagination.pageSize,
      filters,
      sorter
    });
  };

  const showModal = (mode: 'add' | 'edit', user: UserInfo | null = null) => {
    setModalMode(mode);
    setEditingUser(user);
    form.resetFields();
    
    // 如果是添加模式，清空职位列表
    if (mode === 'add') {
      console.log('添加模式：清空职位列表');
      setPositions([]);
    }
    
    if (mode === 'edit' && user) {
      console.log('编辑用户数据:', user);
      // 找到对应的角色ID
      const roleObj = roles.find(r => r.name === user.role);
      console.log('找到的角色:', roleObj);
      
      // 根据部门ID找到对应的部门选项和职位列表
      let departmentValue: string | undefined;
      let departmentPositions: Position[] = [];
      let positionId: number | undefined;
      
      console.log('当前所有部门数据:', allDepartments);
      console.log('用户的部门ID:', user.department);
      console.log('用户的部门类型:', user.deptType);
      console.log('用户的当前状态:', user.status);
      
      // 根据部门类型和ID查找部门
      const deptTypePrefix = user.deptType === 1 ? 'dept' : 
                            user.deptType === 2 ? 'academy' : 'other';
      
      allDepartments.forEach(group => {
        console.log('检查部门组:', group.label);
        group.options.forEach(dept => {
          console.log('检查部门选项:', dept);
          // 使用部门类型前缀和ID匹配
          const expectedValue = `${deptTypePrefix}_${user.department}`;
          console.log('期望的部门值:', expectedValue, '实际部门值:', dept.value);
          
          if (dept.value === expectedValue) {
            console.log('找到匹配的部门:', dept);
            departmentValue = dept.value;
            departmentPositions = dept.positions || [];
            
            // 根据职位名称找到对应的职位ID
            if (departmentPositions.length > 0) {
              const positionObj = departmentPositions.find(pos => pos.positionName === user.position);
              if (positionObj) {
                positionId = positionObj.positionId;
                console.log('找到匹配的职位:', positionObj);
              }
            }
          }
        });
      });

      console.log('设置的部门值:', departmentValue);
      console.log('设置的职位列表:', departmentPositions);
      console.log('找到的职位ID:', positionId);

      // 先设置职位列表
      setPositions(departmentPositions);

      // 然后设置表单值
      const formValues = {
        department: departmentValue,
        position: positionId,
        roleId: roleObj?.id,
        deptType: user.deptType,
        status: user.status, // 确保设置当前状态
      };
      
      console.log('设置的表单值:', formValues);
      form.setFieldsValue(formValues);
    }
    setModalVisible(true);
  };

  // 2. 修改编辑模式的表单提交
  const handleModalOk = async () => {
    try {
      const values = await form.validateFields();
      console.log('表单原始数据:', values);

      if (modalMode === 'add') {
        // 从部门值中解析部门ID
        const [type, id] = values.department.split('_');
        // 使用表单中的 deptType 值，如果没有则根据部门类型推断
        const deptType = values.deptType || (type === 'dept' ? 1 : type === 'academy' ? 2 : 3);
        
        const employeeData = {
          employeeId: values.employeeId,
          username: values.username,
          gender: parseInt(values.gender),
          age: parseInt(values.age),
          birthday: values.birthday.format('YYYY-MM-DD'),
          phoneNumber: values.phoneNumber,
          email: values.email,
          department: parseInt(id),
          position: parseInt(values.position),
          roleId: parseInt(values.roleId),
          deptType: deptType
        };

        console.log('提交到服务器的数据:', employeeData);

        const response = await addEmployee(employeeData);
        if (response.data.code === 1) {
          message.success('添加成功');
          loadUsers();
          setModalVisible(false);
          form.resetFields();
        } else {
          throw new Error(response.data.msg || '添加失败');
        }
      } else if (modalMode === 'edit' && editingUser) {
        // 检查是否在修改自己的信息
        if (currentUser && currentUser.employeeId === editingUser.employeeId) {
          message.error('您不能修改自己的信息，请联系其他管理员进行修改');
          return;
        }
        
        // 从部门值中解析部门ID
        const [type, id] = values.department.split('_');
        const deptType = values.deptType || (type === 'dept' ? 1 : type === 'academy' ? 2 : 3);
        
        // 构建更新数据
        const updateData: any = {
          employeeId: editingUser.employeeId,
          department: parseInt(id),
          position: parseInt(values.position),
          deptType: deptType,
          roleId: parseInt(values.roleId),
          // 始终包含状态字段，如果表单中没有，则使用当前状态
          status: values.status !== undefined ? parseInt(values.status) : editingUser.status
        };
        
        console.log('更新数据:', updateData);
        
        try {
          const response = await updateEmployeeProfile(updateData);
          if (response.data.code === 1) {
            message.success('更新成功');
            loadUsers();
            setModalVisible(false);
          } else {
            message.error(response.data.msg || '更新失败');
          }
        } catch (error: unknown) {
          const apiError = error as ApiError;
          console.error('更新失败:', apiError);
          
          // 处理特定错误消息
          if (apiError.response?.data?.msg) {
            const errorMsg = apiError.response.data.msg;
            message.error(ERROR_MESSAGES[errorMsg] || errorMsg);
          } else if (apiError.message) {
            message.error(apiError.message);
          } else {
            message.error('更新失败，请稍后重试');
          }
        }
      }
    } catch (error: unknown) {
      console.error('操作失败:', error);
      
      if (error instanceof Error) {
        const apiError = error as ApiError;
        if (apiError.response?.data?.msg) {
          const errorMsg = ERROR_MESSAGES[apiError.response.data.msg] || apiError.response.data.msg;
          message.error(errorMsg);
        } else {
          message.error(apiError.message || '操作失败，请重试');
        }
      } else {
        message.error('操作失败，请重试');
      }
    }
  };

  const calculateBirthYear = (age: number) => {
    const currentYear = new Date().getFullYear();
    return currentYear - age;
  };

  const calculateAge = (birthday: dayjs.Dayjs) => {
    return dayjs().diff(birthday, 'year');
  };

  const handleBirthdayChange = (date: dayjs.Dayjs | null) => {
    if (date) {
      const age = calculateAge(date);
      form.setFieldsValue({ age });
    }
  };

  const handleAgeChange = (value: number | null) => {
    if (value) {
      const birthYear = calculateBirthYear(value);
      const currentBirthday = form.getFieldValue('birthday');
      if (currentBirthday) {
        const newBirthday = currentBirthday.year(birthYear);
        form.setFieldsValue({ birthday: newBirthday });
      } else {
        form.setFieldsValue({ 
          birthday: dayjs().year(birthYear).startOf('year') 
        });
      }
    }
  };

  const handleDelete = async (employeeId: string) => {
    try {
      const response = await deleteEmployees([employeeId]);
      if (response.data.code === 1) {
        message.success('删除成功');
        await loadUsers();
      } else {
        message.error(response.data.msg || '删除失败');
      }
    } catch (error: unknown) {
      console.error('删除失败:', error);
      if (error instanceof Error) {
        message.error(error.message || '删除失败');
      } else {
        message.error('删除失败');
      }
    }
  };

  const handleBatchDelete = async () => {
    try {
      const response = await deleteEmployees(selectedRowKeys);
      if (response.data.code === 1) {
        message.success('批量删除成功');
        setSelectedRowKeys([]);
        await loadUsers();
      } else {
        message.error(response.data.msg || '批量删除失败');
      }
    } catch (error: unknown) {
      console.error('批量删除失败:', error);
      if (error instanceof Error) {
        message.error(error.message || '批量删除失败');
      } else {
        message.error('批量删除失败');
      }
    }
  };

  const handleSelectChange = (newSelectedRowKeys: string[], selectedRows: UserInfo[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };

  const getGenderText = (gender: number): string => {
    return gender === 1 ? '男' : '女';
  };

  const getDeptTypeText = (type: number): string => {
    return DEPT_TYPE_MAP[type] || '未知';
  };

  const getStatusText = (status: number): string => {
    return STATUS_MAP[status as keyof typeof STATUS_MAP] || '未知';
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: handleSelectChange,
    getCheckboxProps: (record: UserInfo) => ({
      disabled: record.employeeId === currentUser?.employeeId,
      name: record.username,
    }),
  };

  // 5. 修改表格列定义,确保包含所有字段
  const columns: TableColumn[] = [
    { title: '工号', dataIndex: 'employeeId', key: 'employeeId' },
    { title: '姓名', dataIndex: 'username', key: 'username' },
    {
      title: '性别',
      dataIndex: 'gender',
      key: 'gender',
      render: (value: number) => getGenderText(value)
    },
    { title: '年龄', dataIndex: 'age', key: 'age' },
    { title: '手机号', dataIndex: 'phoneNumber', key: 'phoneNumber' },
    { title: '邮箱', dataIndex: 'email', key: 'email' },
    {
      title: '部门类型',
      dataIndex: 'deptType',
      key: 'deptType',
      render: (value: number) => getDeptTypeText(value)
    },
    { title: '职位', dataIndex: 'position', key: 'position' },
    {
      title: '任职状态',
      dataIndex: 'status',
      key: 'status',
      render: (value: number) => getStatusText(value)
    },
    { title: '账号角色', dataIndex: 'role', key: 'role' },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      render: (_: unknown, record: UserInfo) => {
        const isCurrentUser = currentUser?.employeeId === record.employeeId;
        return (
          <Space size="middle">
            <Button
              type="primary"
              icon={<EditOutlined />}
              onClick={() => showModal('edit', record)}
              disabled={isCurrentUser}
              style={{
                background: isCurrentUser ? '#f0f0f0' : '#1890ff',
                borderColor: isCurrentUser ? '#d9d9d9' : '#1890ff',
                color: isCurrentUser ? '#00000040' : '#ffffff',
                fontSize: '14px',
                padding: '4px 12px',
                height: '32px',
                display: 'flex',
                alignItems: 'center',
                gap: '4px',
                boxShadow: '0 2px 0 rgba(0,0,0,0.1)'
              }}
            >
              编辑
            </Button>
            <Popconfirm
              title="确定要删除该员工吗？"
              onConfirm={() => handleDelete(record.employeeId)}
              okText="确定"
              cancelText="取消"
              disabled={isCurrentUser}
            >
              <Button
                type="primary"
                danger
                icon={<DeleteOutlined />}
                disabled={isCurrentUser}
                style={{
                  background: isCurrentUser ? '#f0f0f0' : '#ff4d4f',
                  borderColor: isCurrentUser ? '#d9d9d9' : '#ff4d4f',
                  color: isCurrentUser ? '#00000040' : '#ffffff',
                  fontSize: '14px',
                  padding: '4px 12px',
                  height: '32px',
                  display: 'flex',
                  alignItems: 'center',
                  gap: '4px',
                  boxShadow: '0 2px 0 rgba(0,0,0,0.1)'
                }}
              >
                删除
              </Button>
            </Popconfirm>
          </Space>
        );
      }
    }
  ];

  return (
    <Layout>
      <div className="p-4">
        <Card>
          <Form layout="inline" className="mb-8">
            <Row gutter={[16, 16]} className="w-full">
              <Col>
                <Form.Item>
                  <Input
                    placeholder="请输入员工编号或姓名"
                    value={filters.keyword}
                    onChange={e => {
                      const value = e.target.value;
                      // 如果输入的是7位数字（工号），清空其他条件
                      if (/^\d{7}$/.test(value)) {
                        setFilters({
                          keyword: value,
                          department: undefined,
                          deptType: undefined,
                          position: undefined
                        });
                      } else {
                        setFilters(prev => ({ ...prev, keyword: value }));
                      }
                    }}
                    style={{ width: 200 }}
                    allowClear
                  />
                </Form.Item>
              </Col>
              
              <Col>
                <Form.Item>
                  <Select
                    placeholder="请选择部门类型"
                    value={filters.deptType}
                    onChange={value => {
                      console.log('选择部门类型:', value);
                      setFilters(prev => ({ 
                        ...prev, 
                        deptType: value,
                        // 选择部门类型时，如果之前是工号查询，清空工号
                        keyword: /^\d{7}$/.test(prev.keyword) ? '' : prev.keyword
                      }));
                    }}
                    style={{ width: 150 }}
                    allowClear
                  >
                    <Option value={1}>职能部门</Option>
                    <Option value={2}>二级学院</Option>
                    <Option value={3}>其他部门</Option>
                  </Select>
                </Form.Item>
              </Col>

              <Col>
                <Form.Item>
                  <Select
                    placeholder="请选择部门"
                    value={filters.department}
                    onChange={value => setFilters(prev => ({ 
                      ...prev, 
                      department: value,
                      // 选择部门时，如果之前是工号查询，清空工号
                      keyword: /^\d{7}$/.test(prev.keyword) ? '' : prev.keyword
                    }))}
                    style={{ width: 200 }}
                    allowClear
                  >
                    {allDepartments.map(group => (
                      <Select.OptGroup key={group.label} label={group.label}>
                        {group.options.map(dept => (
                          <Option key={dept.value} value={dept.value.split('_')[1]}>
                            {dept.label}
                          </Option>
                        ))}
                      </Select.OptGroup>
                    ))}
                  </Select>
                </Form.Item>
              </Col>

              <Col>
                <Form.Item>
                  <Space size="middle">
                    <Button 
                      type="primary" 
                      icon={<SearchOutlined />} 
                      onClick={handleSearch}
                      style={{
                        background: '#1890ff',
                        borderColor: '#1890ff',
                        boxShadow: '0 2px 0 rgba(24,144,255,0.1)'
                      }}
                    >
                      搜索
                    </Button>
                    <Button 
                      onClick={handleReset}
                      style={{
                        border: '1px solid #d9d9d9',
                        boxShadow: '0 2px 0 rgba(0,0,0,0.02)'
                      }}
                    >
                      重置
                    </Button>
                    {currentUser?.role === '超级管理员' && (
                      <Button
                        type="primary"
                        icon={<PlusOutlined />}
                        onClick={() => showModal('add')}
                        style={{
                          background: '#52c41a',
                          borderColor: '#52c41a',
                          boxShadow: '0 2px 0 rgba(82,196,26,0.1)'
                        }}
                      >
                        新增员工
                      </Button>
                    )}
                  </Space>
                </Form.Item>
              </Col>
            </Row>
          </Form>

          <div className="mt-6">
            <Table
              rowKey="employeeId"
              columns={columns}
              dataSource={users}
              loading={loading}
              pagination={{
                ...pagination,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: total => `共 ${total} 条记录`
              }}
              onChange={handleTableChange}
            />
          </div>
        </Card>
        
        <StyledModal
          title={modalMode === 'add' ? '新增用户' : '编辑用户'}
          open={modalVisible}
          onOk={handleModalOk}
          onCancel={() => setModalVisible(false)}
          width={600}
          style={{ 
            top: '5vh',
            paddingBottom: 0
          }}
          styles={{ 
            mask: { backgroundColor: 'rgba(0, 0, 0, 0.45)' },
            body: { padding: '24px' }
          }}
        >
          <Form
            form={form}
            layout="vertical"
          >
            {modalMode === 'add' ? (
              <>
                <Form.Item
                  name="employeeId"
                  label="工号"
                  rules={[
                    { required: true, message: '请输入工号' },
                    { 
                      pattern: /^\d{7}$/, 
                      message: '工号必须是7位数字' 
                    },
                    {
                      validator: async (_, value) => {
                        if (value && !/^\d{7}$/.test(value)) {
                          return Promise.reject();
                        }
                        // 确保 allUsers 是数组再调用 some 方法
                        if (value && Array.isArray(allUsers) && allUsers.some(user => user.employeeId === value)) {
                          return Promise.reject('该工号已存在');
                        }
                        return Promise.resolve();
                      }
                    }
                  ]}
                >
                  <Input 
                    maxLength={7}
                    placeholder="请输入7位数字工号"
                  />
                </Form.Item>
                <Form.Item
                  name="username"
                  label="姓名"
                  rules={[{ required: true, message: '请输入姓名' }]}
                >
                  <Input />
                </Form.Item>
                <Form.Item
                  name="gender"
                  label="性别"
                  rules={[{ required: true, message: '请选择性别' }]}
                >
                  <Select>
                    <Option value={1}>男</Option>
                    <Option value={2}>女</Option>
                  </Select>
                </Form.Item>
                <Form.Item
                  name="birthday"
                  label="生日"
                  rules={[{ required: true, message: '请选择生日' }]}
                >
                  <DatePicker 
                    style={{ width: '100%' }}
                    format="YYYY-MM-DD"
                    onChange={handleBirthdayChange}
                    disabledDate={current => {
                      return current && (
                        current > dayjs().endOf('day') ||
                        current < dayjs().subtract(100, 'year')
                      );
                    }}
                  />
                </Form.Item>
                <Form.Item
                  name="age"
                  label="年龄"
                  rules={[
                    { required: true, message: '请输入年龄' },
                    { type: 'number', min: 18, max: 100, message: '年龄必须在18到100之间' }
                  ]}
                >
                  <InputNumber 
                    style={{ width: '100%' }}
                    onChange={handleAgeChange}
                  />
                </Form.Item>
                <Form.Item
                  name="phoneNumber"
                  label="手机号"
                  rules={[
                    { required: true, message: '请输入手机号' },
                    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号' }
                  ]}
                >
                  <Input />
                </Form.Item>
                <Form.Item
                  name="email"
                  label="邮箱"
                  rules={[
                    { required: true, message: '请输入邮箱' },
                    { type: 'email', message: '请输入有效的邮箱地址' }
                  ]}
                >
                  <Input />
                </Form.Item>
              </>
            ) : null}
            <Form.Item
              name="department"
              label="部门"
              rules={[{ required: true, message: '请选择部门' }]}
            >
              <Select
                onChange={(value) => {
                  console.log('部门选择触发:', value);
                  // 确保值存在且不为空
                  if (value) {
                    // 直接在这里处理部门选择逻辑
                    let selectedDept: Department | undefined;
                    let deptTypeValue: number | undefined;
                    
                    // 查找选中的部门
                    allDepartments.forEach(group => {
                      group.options.forEach(dept => {
                        if (dept.value === value) {
                          selectedDept = dept;
                          if (dept.type === 'dept') deptTypeValue = 1;
                          else if (dept.type === 'academy') deptTypeValue = 2;
                          else if (dept.type === 'other') deptTypeValue = 3;
                        }
                      });
                    });
                    
                    console.log('选中部门:', selectedDept);
                    console.log('部门类型:', deptTypeValue);
                    
                    if (selectedDept && selectedDept.positions && selectedDept.positions.length > 0) {
                      console.log('岗位列表:', selectedDept.positions);
                      setPositions(selectedDept.positions);
                      form.setFieldsValue({ deptType: deptTypeValue });
                    } else {
                      console.log('无可用岗位');
                      setPositions([]);
                    }
                  }
                }}
                placeholder="请选择部门"
                options={allDepartments}
                style={{ width: '100%' }}
              />
            </Form.Item>
            {/* 隐藏的部门类型字段 */}
            <Form.Item
              name="deptType"
              hidden
            >
              <Input type="hidden" />
            </Form.Item>
            <Form.Item
              name="position"
              label="职位"
              rules={[{ required: true, message: '请选择职位' }]}
            >
              <Select
                placeholder="请选择职位"
                disabled={positions.length === 0}
                style={{ width: '100%' }}
              >
                {positions.map(pos => (
                  <Option 
                    key={pos.positionId} 
                    value={pos.positionId}
                  >
                    {pos.positionName}
                  </Option>
                ))}
              </Select>
            </Form.Item>
            <Form.Item
                name="roleId"
                label="账号角色"
                rules={[{ required: true, message: '请选择账号权限' }]}
              >
                <Select>
                  {Array.isArray(roles) && roles.map(role => (
                    <Option key={role.id} value={role.id}>
                      {role.name}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            {/* 修改表单项,添加任职状态选择 */}
            <Form.Item
              name="status"
              label="任职状态"
              rules={[{ required: true, message: '请选择任职状态' }]}
              initialValue={modalMode === 'edit' && editingUser ? editingUser.status : 0}
            >
              {modalMode === 'edit' && editingUser ? (
                // 编辑模式下使用按钮组
                <Radio.Group 
                  buttonStyle="solid"
                  disabled={editingUser.status === 1 || editingUser.status === 2}
                >
                  {/* 可选状态 */}
                  <Radio.Button 
                    value={1} 
                    disabled={editingUser.status === 1}
                  >
                    正式员工
                  </Radio.Button>
                  <Radio.Button 
                    value={2} 
                    disabled={editingUser.status === 2}
                  >
                    离职
                  </Radio.Button>
                </Radio.Group>
              ) : (
                // 添加模式下只能选择试用期
                <Radio.Group buttonStyle="solid">
                  <Radio.Button value={0}>试用期员工</Radio.Button>
                </Radio.Group>
              )}
            </Form.Item>
          </Form>
        </StyledModal>
      </div>
    </Layout>
  );
};

export default UserInfoPage;